package com.wstuo.common.service;

import org.apache.log4j.Logger;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;


/**
 * This class is intended to be a base class for all business service classes.
 *
 * @version 1.00 
 * @author wstuo.com
 */
public class BaseService {

    private static final Logger LOGGER = Logger.getLogger(BaseService.class);
    private String username = "Unknown User";
    private String clientHostAddress = "Unknown Host";

    /**
     * @return String the username
     */
    public String getUsername() {

        if (SecurityContextHolder.getContext().getAuthentication() != null) {

            Object principal = SecurityContextHolder.getContext()
                                                    .getAuthentication()
                                                    .getPrincipal();

            if (principal instanceof UserDetails) {

                username = ((UserDetails) principal).getUsername();
            } else {

                username = principal.toString();
            }
        }

        return username;
    }

    /**
     * @return String the clientHostAddress
     */
    protected String getClientHostAddress() {

        if (SecurityContextHolder.getContext().getAuthentication() != null) {

            Object details = SecurityContextHolder.getContext()
                                                  .getAuthentication()
                                                  .getDetails();

            if (details instanceof WebAuthenticationDetails) {

                clientHostAddress = ((WebAuthenticationDetails) details)
                    .getRemoteAddress();
            }
        }

        return clientHostAddress;
    }

    protected void logAuditTrail(String actionDesc) {

        StringBuilder logMessage = new StringBuilder();

        logMessage.append(getUsername());
        logMessage.append(" from ");
        logMessage.append(getClientHostAddress());
        logMessage.append(": ");
        logMessage.append(actionDesc);

        LOGGER.info(logMessage.toString());
    }
}